<?php
require_once "facebook.php";

/**
 * Custom Facebook class
 */  
class FacebookToolbox extends Facebook
{
    /**
     * @var  $app_access_token The App access token
     */         
    protected $app_access_token;
    
    /**
     * @var $privilegies The defaults privilegies
     */         
    protected $privilegies = 'publish_stream,user_likes,offline_access';

    /**
     * @var $debug_level Level for debugging
     */         
    protected $debug_level;
    
    public function setDebugLevel($level){
        $this->debug_level=$level;  
    }
    
    /**
     * Logs
     * 
     * @params $pLevel Level for log
     * @params $pMsg Message to log               
     */         
    protected function debug($pLevel,$pMsg){
        if($pLevel <= $this->debug_level){
            $pMsg = print_r($pMsg,true);
            $line = "";
            $APP_DEBUG_TOKEN = APP_DEBUG_TOKEN;
            
            if(stripos($pMsg,'FacebookToolbox::')!==false){
                $line = "\n".str_pad('',80,'.');
                $pMsg = "{$line}\n{$APP_DEBUG_TOKEN} => {$pMsg}{$line}";
            }
            error_log("\n{$pMsg}", 3, APP_LOG);
        }
    }
   
    /**
     * Obtenemos el access_token de la aplicacion para la conexion
     *
     */              
    public function getAppAccessToken(){
    	$this->debug(3,__METHOD__);
    	$args=func_get_args();$this->debug(3,$args);
    	
        $params['grant_type']='client_credentials';
    	$params['client_id']=$this->getAppId();
    	$params['client_secret']=$this->getApiSecret();
        $this->debug(3,$params);
            	
    	$url = $this->getUrl('graph','/oauth/access_token',$params);
        $this->debug(3,$url);
        
        $access_token = file_get_contents($url);
        $this->debug(3,$access_token);

        $this->app_access_token = explode('=',$access_token);
        $this->app_access_token = $this->app_access_token[1];
        
        return  $access_token;
    }

    public function getLoginUrl($params=false){
    	$this->debug(3,__METHOD__);
    	$args=func_get_args();$this->debug(3,$args);
            
        $params = array();
        $params['redirect_uri'] = FB_APP_BASE_URL;
        $params['scope'] = $this->privilegies;
        $this->debug(3,$params);
        
        $url = parent::getLoginUrl($params);
        $this->debug(3,$url);
        
        return $url;
    }

    public function isLogued(){
    	$this->debug(3,__METHOD__);
    	$args=func_get_args();$this->debug(3,$args);
            
        $user =  $this->getUser();
        $this->debug(3,$user);    
        
        return $user;    
    } 
    
   
    /**
     * Post a feed to the wall
     *
     */              
    public function post($uid,$params){
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
                
        $this->api("/{$uid}/feed","POST",$params);
    }
    
    
    /**
     * Eliminamos una peticion de registracion en la aplicacion
     */         
    public function deleteRequest($reqid){
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);        
                
        $this->api("/{$reqid}/feed","delete");        
    }
  
    /**
     * Maneja las peticiones
     */         
    public function getRequests(){
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
        $this->debug(3,$_GET);
        $this->debug(3,$_REQUEST); 
        
        
        $request_ids = $_GET["request_ids"];
       	$signed_request = $_REQUEST["signed_request"];
       	$data_signed = $this->parseSignedRequest($signed_request);
       	
        $request =  array(
            'request_id' => $request_ids,
            'data_signed' => $data_signed
        );
        $this->debug(3,$request); 
        
        return $request;
	
    }


    /**
     * revisamos los permisos 
     */         
    public function checkPrivilegies($privilegies){
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
            
        $fql = "select {$privilegies} from permissions where uid = me()  ";
        $this->debug(3,$fql); 
                
        $privilegies = $this->fqlRun($fql);
        $allow = true;
        foreach($privilegies[0] as $p){
            $allow &= $p;
        }
        return $allow;    
    }
    
    /**
     * reviso si nos gusta esta pagina
     */         
    public function checkLikePage($pageId){
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
            
        $fql = "select uid from page_fan where uid = me() and page_id = '{$pageId}' ";
        $this->debug(3,$fql); 
                
        $pages = $this->fqlRun($fql);
        return count($pages);
    }
    
    public function fqlRun($query){
        $this->debug(2,__METHOD__);
        $args=func_get_args();$this->debug(2,$args);
            
        $params=array();
        $params['method']='fql.query';
        $params['query']=$query;
        $this->debug(2,$params);  
        
        $result = $this->api($params);
        $this->debug(2,$result); 
        
        return $result; 
    }
    
    
    
    // offline_access
    public function setUserAccessToken($fbId){  // 596614683 mariogarcia.ar
        $accounts = $this->getPersistUserAccessToken();
        $access_token = $accounts[$fbId];
        $this->setAccessToken($access_token);
    }
    public function getPersistUserAccessToken(){
        $file = FACEBOOK_TOOLBOX_USERS_DATA;
        $accounts = array();
        if(file_exists($file)){
            $accounts_serialize = file_get_contents($file);
            $accounts = unserialize($accounts_serialize);
        }
        return $accounts;
    }  
    public function persistUserAccessToken(){
        $file = FACEBOOK_TOOLBOX_USERS_DATA;
        $access_token = $this->getAccessToken();
        
        $accounts = $this->getPersistUserAccessToken();
        // esta en el data
        $accounts[$this->getUser()]=$access_token;
        file_put_contents($file, serialize($accounts));
    }       
}
